package com.leetcode.problems056;

import java.util.Arrays;

/**
 * https://leetcode-cn.com/problems/merge-intervals/
 * @Date 2021/12/09 14:34
 * @Author ghery
 * @Version V1.0
 */
public class Solution {

    public int[][] merge(int[][] intervals) {
        Arrays.sort(intervals, (first, end) -> {
            if(first[0] < end[0]){
                return -1;
            }
            if(first[0] == end[0]){
                return first[1] - end[1];
            }
            return 1;
        });
        int[][] ans = new int[intervals.length][2];
        ans[0] = intervals[0];
        int ansLen = 1;
        int preIndex = 0;
        for (int i = 1; i < intervals.length; i++) {
            if(intervals[i][0] <= ans[preIndex][1]){
                ans[preIndex][1] = Math.max(ans[preIndex][1],intervals[i][1]);
            }else{
                ans[++preIndex] = intervals[i];
                ansLen++;
            }
        }
        int[][] ans1 = new int[ansLen][2];
        for (int i = 0; i < ansLen; i++) {
            ans1[i] = ans[i];
        }

        return ans1;
    }



    public static void main(String[] args) {
        int[][] nums = {{1,4},{1,4},{2,5},{1,4}};
        int[][] res = new Solution().merge(nums);
        System.out.print("[");
        for (int[] re : res) {
            System.out.print("[");
            for (int i = 0; i < re.length; i++) {
                System.out.print(re[i]);
                if(i != re.length - 1){
                    System.out.print(",");
                }
            }
            System.out.print("]");
        }
        System.out.println("]");
    }
}
